package com.weizhong.update.service;

import java.util.HashMap;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import com.weizhong.update.R;
import com.weizhong.update.model.AppEntity;
import com.weizhong.update.receiver.BootReceiver;
import com.weizhong.update.util.AppUpdateDetail;
import com.weizhong.update.util.DialogUpdateActivity;
import com.weizhong.update.util.Logger;

import android.R.integer;
import android.app.DownloadManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

public class AppUpdateDownloadListener {
	public static final Uri CONTENT_URI = Uri.parse("content://downloads/my_downloads");  
	private static final String TAG = "AppUpdateDownloadListener";
	public static ConcurrentHashMap<String, Long> hashMap = new ConcurrentHashMap<String, Long>();
	public static ConcurrentHashMap<String, Boolean> StatusMap = new ConcurrentHashMap<String,Boolean>();
	private Context mContext = null;
	
	// 通知栏
	private NotificationManager updateNotificationManager = null;

	// 通知栏跳转Intent
	private Intent updateIntent = null;
	private Notification updateNotification = null;
	private final int NOTIFY_ID = 1;
	private int oldstatus = -2000;
	private DownloadManager dowanloadmanager = null;
	private int downloadSize = 0;
	private AppUpdateDetail appUpdateDetail;
	private int appNeedDownloadSize = 0;
	private int downloadFailedTimes = 0;

	AppDownloadChangeObserver downloadObserver = new AppDownloadChangeObserver(null);
	public static int downloadProcess = 0;

	public AppUpdateDownloadListener(Context context){
		mContext = context;
		mContext.getContentResolver().registerContentObserver(CONTENT_URI, true, downloadObserver);
		appUpdateDetail = new AppUpdateDetail(mContext);
		appNeedDownloadSize = appUpdateDetail.getDownloadSize();
		initMap(appUpdateDetail);
	}
	
	public int addToListener(long downloadid,String packageName){
		Logger.i(TAG, "addToListener: " + "downloadid is " + downloadid + "packageName is " + packageName);
		hashMap.put(packageName, downloadid);
		StatusMap.put(packageName, false);
        //更新数据库
        AppEntity appEntity = new AppEntity();
        appEntity.setPackageName(packageName);
        appEntity.setDownloadID((int)downloadid);
        appUpdateDetail.updateDownloadID(appEntity);
		return 1;
	}
	
	public void initMap(AppUpdateDetail appUpdateDetail){
		Log.i(TAG, "init Map");
		appUpdateDetail.setDownloadIDToMap();
	}
	
	public void destroyMap(){
		Log.i(TAG, "destroy Map");
		hashMap = new ConcurrentHashMap<String, Long>();
		StatusMap = new ConcurrentHashMap<String,Boolean>();
	}
	
    /**
  	 * notification提示
  	 * @param intent
  	 */
  	private void createNotification(Context context,int status,int pos){	
  		Logger.i(TAG, "createNotification");
  		downloadSize = BootReceiver.appDownloadSize;
  		pos += ((int)(((double)(downloadSize)/(BootReceiver.appSize))*100));
  		if (this.updateNotification!=null) return;
  		if(null == this.updateNotificationManager){
  			this.updateNotificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
  		}
  		this.updateNotification = new Notification();  		
  		updateNotification.flags= Notification.FLAG_NO_CLEAR;
  		// 设置下载过程中，点击通知栏，回到主界面 this, UpdateActivity.class
  		RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.download_notification_layout);  
        contentView.setTextViewText(R.id.fileName,getStatusText(status));  
        contentView.setProgressBar(R.id.progress, 100, pos, false);
        // 指定个性化视图  
        updateNotification.contentView = contentView;
  		// 设置通知栏显示内容
  		updateNotification.icon = R.drawable.ic_launcher;
  		Intent intent = new Intent(context,DialogUpdateActivity.class);
  		intent.putExtra("AppUpdateDownloading", true);
  		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent pendingIntent  = PendingIntent.getActivity(context, 0, intent, 0);  
        updateNotification.contentIntent = pendingIntent;
  		updateNotification.tickerText = context.getResources().getText(R.string.app_update_string);
  		// 通知不被清理
  		updateNotification.flags |= Notification.FLAG_NO_CLEAR;
  		// 发出通知
  		updateNotificationManager.notify(NOTIFY_ID, updateNotification);  	
  		oldstatus = status;
  	}
  	
  	private String getStatusText(int status){
  		String txt = mContext.getResources().getString(R.string.apk_notification_string);

  		switch(status) {     
        case DownloadManager.STATUS_PAUSED: 
        	txt += "(等待中)"; 
            break;
        case DownloadManager.STATUS_PENDING:
            txt += "(等待中)";
            break;
        case DownloadManager.STATUS_RUNNING:       			
            //正在下载，不做任何事情
        	txt += "(下载中)";
            break;       			
        case DownloadManager.STATUS_SUCCESSFUL:     
            //完成    
        	txt += "(已完成)";
            break;     
        case DownloadManager.STATUS_FAILED:     
            //清除已下载的内容，重新下载    
            txt += "(失败)";
            break;     
        }  		
  		return txt;
  	}
  	
  	private void setNotificationProgressStatus(int status,int pos){
  		if (pos > 100) pos = 100;
  		if (this.updateNotification == null){
  			createNotification(mContext,status,pos);
  			if (this.updateNotification == null) return;
  		}
  		
  		this.updateNotification.contentView.setProgressBar(R.id.progress, 100, pos, false);
  		this.updateNotification.contentView.setTextViewText(R.id.rate, "" + pos + "%");
  		if (oldstatus != status){
  			this.updateNotification.contentView.setTextViewText(R.id.fileName,getStatusText(status));
  			oldstatus = status;
  		}
  		updateNotificationManager.notify(NOTIFY_ID, updateNotification);
  	}
	
 	public int queryAppDownloadStatus() {
 		 //监听实时下载进度，查看当前下载状态：是否已经断开，或者下载失败等等
        int appDownloadSize = appNeedDownloadSize;
        Log.i(TAG, "appDownloadSize: " + appDownloadSize + "hashMap size: " + hashMap.size());
        int downloadSize = 0;
        
 		for (Entry<String, Long> entry : hashMap.entrySet()) {
 			String packageName = entry.getKey();
 			long downloadId = entry.getValue();
 			Log.i(TAG,"queryAppDownloadStatus: " +  "packageName: " + packageName +
				"downloadid is " + downloadId);
 	 		DownloadManager.Query query = new DownloadManager.Query();
 	 		query.setFilterById(downloadId);
 	 		Cursor c = getDownloadManager().query(query); 	 	  
 	 		if(c!=null&&c.moveToFirst()) { 
 	 			//找到数据
 	 		   int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));     
 	           int reasonIdx = c.getColumnIndex(DownloadManager.COLUMN_REASON);    
 	           int titleIdx = c.getColumnIndex(DownloadManager.COLUMN_TITLE);    
 	           int fileSizeIdx = c.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES);        
 	           int bytesDLIdx =   c.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);    
 	           String title = c.getString(titleIdx);    
 	           int fileSize = c.getInt(fileSizeIdx);    
 	           int bytesDL = c.getInt(bytesDLIdx);
 	           downloadSize += bytesDL;
 	           // Translate the pause reason to friendly text.    
 	           int reason = c.getInt(reasonIdx);    
 	           StringBuilder sb = new StringBuilder();    
 	           sb.append(title).append("\n");   
 	           sb.append("Downloaded ").append(bytesDL).append(" / " ).append(fileSize); 
 	           Log.d("TAG", sb.toString());    
 	           switch(status) {     
 	           case DownloadManager.STATUS_PAUSED: 
 	               Log.v(TAG, "下载暂停"); 
 	               //setNotificationProgressStatus(status,(int)(((double)(bytesDL)/appSize)*100));
 	               break;
 	           case DownloadManager.STATUS_PENDING:
 	               Log.v(TAG, "准备下载");
 	               //setNotificationProgressStatus(status,(int)(((double)(bytesDL)/appSize)*100));
 	               break;
 	           case DownloadManager.STATUS_RUNNING:       			
 	               //正在下载，不做任何事情      			
 	               break;       			
 	           case DownloadManager.STATUS_SUCCESSFUL:     
 	 	 			if(!(StatusMap.get(packageName).booleanValue())){
 	 	               Log.v(TAG, packageName + "下载完成");
 	 	        	   if(appUpdateDetail == null){
 	 	        		   appUpdateDetail = new AppUpdateDetail(mContext);
 	 	        	   }
        			   StatusMap.put(packageName, true);
 	 	        	   //下载完成更新数据库
 	 	        	   AppEntity appEntity = new AppEntity();
 	 	        	   appEntity.setPackageName(packageName);
 	 	        	   appEntity.setDownloadSuccess(true);
 	 	        	   appUpdateDetail.updateDownloadResult(appEntity);
 	 	        	   
 					   Intent intent = new Intent("com.wz.bubble.app_download");
 					   mContext.sendBroadcast(intent);
 	 	 			}

 	               break;
 	           case DownloadManager.STATUS_FAILED:     
 	               //清除已下载的内容，重新下载 
 	               Log.v(TAG, "STATUS_FAILED reason: " + reason);
 	               getDownloadManager().remove(downloadId);
 	               if(downloadFailedTimes < 3){
 	            	  downloadFailedTimes++;
 	            	  Toast.makeText(mContext, "应用更新文件下载异常中断，", Toast.LENGTH_LONG).show();
 	               }
 	               
 	        	   if(appUpdateDetail == null){
 	        		   appUpdateDetail = new AppUpdateDetail(mContext);
 	        	   }
 	        	   
 	 			   StatusMap.put(packageName, false);
 	 			   
 	        	   //下载失败更新数据库
 	        	   AppEntity appEntity = new AppEntity();
 	        	   appEntity.setPackageName(packageName);
 	        	   appEntity.setDownloadSuccess(false);
 	        	   appUpdateDetail.updateDownloadResult(appEntity);
 	        	   appEntity.setDownloadID(-1);
 	        	   appUpdateDetail.updateDownloadID(appEntity);
				   Intent intent = new Intent("com.wz.bubble.app_download");
				   mContext.sendBroadcast(intent);
 	               break;
 	           }
 	 		}
 	 	    if (c!=null) c.close();
 	 	    c = null;
 		}

 		if(appDownloadSize == 0){
 			downloadProcess = 100;
 			setNotificationProgressStatus(DownloadManager.STATUS_RUNNING,100);
 		}else {
 			downloadProcess = (int)(((double)(downloadSize)/appDownloadSize)*100);
 			setNotificationProgressStatus(DownloadManager.STATUS_RUNNING,downloadProcess);
		}

		if ((downloadSize == appDownloadSize) || (appDownloadSize == 0)){
 			Logger.i(TAG, "all app download done.");
 			downloadProcess = 100;
 			//取消通知栏
 			cancelNotification();
 			//退出downloadobserver
 			mContext.getContentResolver().unregisterContentObserver(downloadObserver);
 			//下载完成,发送广播更新
 			Intent intent = new Intent("com.wz.bubble.app_update");
 			mContext.sendBroadcast(intent);
 			return 1;
		}

 		return 1;
 	}
 	
 	/**
 	 * 
 	 * @param appDownloadId
 	 * @return
 	 */
 	public int getDownloadStatus(long appDownloadId){
 		DownloadManager.Query query = new DownloadManager.Query();
 		query.setFilterById(appDownloadId);
 		Cursor c = getDownloadManager().query(query);
 		int status = 0;
 		if(c!=null&&c.moveToFirst()) { 
 			//找到数据
 		   status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));     
 		}
 		return status;
 	}
 	
	/**
     * 退出notification
     */
    private void cancelNotification(){
    	if(null!=updateNotificationManager){
    		if (null!=updateNotification){
    			updateNotificationManager.cancel(NOTIFY_ID);
    			updateNotification = null;
    		}
    	}
    }
 	
	private DownloadManager getDownloadManager(){
		if (dowanloadmanager == null)
			dowanloadmanager = (DownloadManager)mContext.getSystemService(mContext.DOWNLOAD_SERVICE);
		return dowanloadmanager;
	}
	
    private class AppDownloadChangeObserver extends ContentObserver {
    	
        public AppDownloadChangeObserver(Uri uri) {
            super(new Handler());            
        }
        
        @Override
        public void onChange(boolean selfChange) {
            //查询需要监听的字段
       	    queryAppDownloadStatus();     
        }
    }
}